package com.msconfig.mvp.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.geo.msconfig.R;
import com.msconfig.bean.deviceInfoBean.TagDeviceInfo;
import com.msconfig.device.CommandParseManage;
import com.msconfig.device.CommandSendManage;
import com.msconfig.device.DeviceManage;
import com.msconfig.device.GetSendCommandList;
import com.msconfig.device.TagSendCommand;
import com.msconfig.event.DeviceUpdateEvent;
import com.msconfig.event.OtherCommunicationDialogDismissEvent;
import com.msconfig.event.TimeZoneDialogDismissEvent;
import com.msconfig.mvp.view.activity.SetupOtherCommunicationDialogActivity;
import com.msconfig.mvp.view.activity.SetupOtherTimeZoneDialogActivity;
import com.msconfig.mvp.view.activity.base.BaseMvpFragment;
import com.msconfig.mvp.view.activity.base.BasePresenter;
import com.msconfig.utils.IsNumAndPointUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import static android.view.View.VISIBLE;
import static com.msconfig.mvp.view.fragment.SetupSurveyStationFragment.COMMUNICATIONSETUP;

public class SetupOtherFragment extends BaseMvpFragment implements View.OnClickListener {
    private FrameLayout flLoading;
    private ImageView ivLoading;
    private Animation setupAnim;
    private ImageView ivCommonBack;
    private TextView tvCommonTitle;
    private ConstraintLayout clCommunication;
    private RelativeLayout rlTimeZone;
    private TextView tvTimeZone;
    private RelativeLayout rlCommunicationSetup;
    private TextView tvCommunicationSetup;
    private RelativeLayout rlServerAdress;
    private EditText etServerAdress;
    private RelativeLayout rlPort;
    private EditText etPort;
    private Button btnDetermine;
    private String[] commands;
    private int index;
    private int type;
    private Context context;
    private TagDeviceInfo deviceInfo;

    private MyHandler myHandler;
    private boolean isSetupDefail;
    protected static final int MSG_SET_UP_DEFAIL =1;//设置失败
    public static final String TIMEZONE = "rlTimeZone";



    //负责更新UI
    private static class MyHandler extends Handler {
        WeakReference<SetupOtherFragment> weakReference;
        private MyHandler(SetupOtherFragment fragment) {
            weakReference = new WeakReference<SetupOtherFragment>(fragment);
        }
        @Override
        public void handleMessage(Message msg) {
            SetupOtherFragment fragment = weakReference.get();
            if (fragment != null) {
                switch (msg.what) {
                    case MSG_SET_UP_DEFAIL:
                        if(fragment.flLoading.getVisibility()==VISIBLE){//动画还在，说明设置事件过久设置失败
                            fragment.stopAnim();
                            fragment.isSetupDefail=true;
                            fragment.showToast(R.string.toast_setup_defail);
                        }
                        break;
                }
            }
        }
    }


    public static SetupOtherFragment newInstance() {
        Bundle args = new Bundle();
        SetupOtherFragment fragment = new SetupOtherFragment();
        fragment.setArguments(args);
        return fragment;
    }

    //当Activity与fragment建立关联时调用
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showSetupOtherTimeZone(TimeZoneDialogDismissEvent event) {
        tvTimeZone.setText(event.getName());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showSetupOtherCommunication(OtherCommunicationDialogDismissEvent event) {
        String type=event.getName();
        tvCommunicationSetup.setText(type);
        if(type.equals(getString(R.string.tcp_client)) || type.equals(getString(R.string.tcp_server))){
            clCommunication.setVisibility(View.VISIBLE);
        }else{
            clCommunication.setVisibility(View.GONE);
        }
    }



    @Override
    protected int getLayoutId() {
        return R.layout.layout_fragment_setup_other;
    }

    @Override
    protected void initView(View view) {
        ivCommonBack=view.findViewById(R.id.iv_common_back);
        tvCommonTitle=view.findViewById(R.id.tv_common_title);
        clCommunication=view.findViewById(R.id.cl_communication);
        rlTimeZone = (RelativeLayout)view.findViewById( R.id.rl_time_zone );
        tvTimeZone = (TextView)view.findViewById( R.id.tv_time_zone );
        rlCommunicationSetup = (RelativeLayout)view.findViewById( R.id.rl_communication_setup );
        tvCommunicationSetup = (TextView)view.findViewById( R.id.tv_communication_setup );
        rlServerAdress = (RelativeLayout)view.findViewById( R.id.rl_server_adress );
        etServerAdress = (EditText)view.findViewById( R.id.et_server_adress );
        rlPort = (RelativeLayout)view.findViewById( R.id.rl_port );
        etPort = (EditText)view.findViewById( R.id.et_port );
        btnDetermine = (Button)view.findViewById( R.id.btn_determine );
        flLoading=view.findViewById(R.id.fl_loading);
        ivLoading = view.findViewById(R.id.iv_loading);


    }

    @Override
    protected void initListener(View view) {
        ivCommonBack.setOnClickListener(this);
        rlTimeZone.setOnClickListener( this );
        rlCommunicationSetup.setOnClickListener( this );
        rlServerAdress.setOnClickListener( this );
        rlPort.setOnClickListener( this );
        btnDetermine.setOnClickListener( this );
    }

    @Override
    protected void initData() {
        tvCommonTitle.setText(R.string.title_other);
        deviceInfo= CommandParseManage.getInstance().getDeviceInfo();

    }

    @Override
    public void onClick(View v) {
        if(v==rlTimeZone){
            Intent intent=new Intent(getActivity(), SetupOtherTimeZoneDialogActivity.class);
            intent.putExtra(TIMEZONE,tvTimeZone.getText().toString().trim());
            startActivity(intent);
        }else if(v==rlCommunicationSetup){
            Intent intent=new Intent(getActivity(), SetupOtherCommunicationDialogActivity.class);
            intent.putExtra(COMMUNICATIONSETUP,tvCommunicationSetup.getText().toString().trim());
            startActivity(intent);
        }else if(v==rlServerAdress){

        }else if(v==rlPort){

        }else if(v==btnDetermine){
            onClickBtnDetermine();
        }else if(v==ivCommonBack){
            backTo();
        }
    }



    //GETALL成功
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void showAnalysisGNSSDataSuccess(DeviceUpdateEvent.UpdateDialogGetRtkSuccessStatus event) {
        if(!DeviceManage.getInstance().isConnected())
            return;
        tvTimeZone.setText(deviceInfo.otherInfo.mTimeZone);
        String type="";
        int communicationSetup= Integer.parseInt(deviceInfo.surveyInfo.mCommunicationSetup);
        switch (communicationSetup){
            case 0:
                type=getString(R.string.close);
                clCommunication.setVisibility(View.GONE);
                break;
            case 1:
                type=getString(R.string.tcp_client);
                clCommunication.setVisibility(View.VISIBLE);
                break;
            case 2:
                clCommunication.setVisibility(View.VISIBLE);
                type=getString(R.string.tcp_server);
                break;
        }
        tvCommunicationSetup.setText(type);
        etServerAdress.setText(deviceInfo.surveyInfo.mServerAdress);
        etPort.setText(deviceInfo.surveyInfo.mServerPort);
    }

    //开始动画
    public void startAnim(){
        setupAnim = AnimationUtils.loadAnimation(context, R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
        setupAnim.setInterpolator(interpolator);
        if (setupAnim != null) {
            btnDetermine.setEnabled(false);
            flLoading.setVisibility(VISIBLE);
            ivLoading.startAnimation(setupAnim);  //开始动画
        }
    }

    //停止动画
    private void stopAnim() {
        if (setupAnim != null) {
            btnDetermine.setEnabled(true);
            setupAnim=null;
            flLoading.setVisibility(View.GONE);
            ivLoading.clearAnimation();
        }
    }


    private void onClickBtnDetermine() {
        isSetupDefail=false;

        if(!DeviceManage.getInstance().isConnected()){
            Toast.makeText(context, R.string.toast_isdisconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        String zone = tvTimeZone.getText().toString().trim();
        if(zone.equals("")){
            Toast.makeText(context, R.string.toast_choose_zone, Toast.LENGTH_SHORT).show();
            return;
        }
        int zoneType= Integer.parseInt(zone);
        String communicatuion = tvCommunicationSetup.getText().toString().trim();
        if(communicatuion.equals("")){
            Toast.makeText(context, R.string.toast_choose_comm, Toast.LENGTH_SHORT).show();
            return;
        }
        if(communicatuion.equals(getString(R.string.close))){
            type=0;
        }else if(communicatuion.equals(getString(R.string.tcp_client))){
            type=1;
        }else if(communicatuion.equals(getString(R.string.tcp_server))){
            type=2;
        }
        String serverAdress = etServerAdress.getText().toString().trim();
        if(!IsNumAndPointUtil.isNumOrPoint(serverAdress)){
            Toast.makeText(context, "请输入正确格式的服务器地址！", Toast.LENGTH_SHORT).show();
            return;
        }
        String serverPort = etPort.getText().toString().trim();
        //开始设置动画
        startAnim();
        //得到发送命令的集合
        ArrayList<TagSendCommand> sendCommandList= GetSendCommandList.getOtherCommandList(zoneType,type,serverAdress,serverPort);
        //设置发送命令额集合
        CommandSendManage.getInstance().setSendCommandList(sendCommandList);
        //开始发送命令
        CommandSendManage.getInstance().startSendCommand();

        //3s后判断有没有数据返回，没有代表设置失败
        myHandler = new MyHandler(this);
        myHandler.sendEmptyMessageDelayed(MSG_SET_UP_DEFAIL,8000);
    }


    //设置全部命令成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setupAllCommandSucc(DeviceUpdateEvent.DeviceCommandSendStatus event) {
        if(isSetupDefail)//3s内没有得到消息显示设置失败，防止数据延迟之后回来设置成功
            return;

        if(event.getStatus()==2){//超时，发送失败
            stopAnim();
            Toast.makeText(context,event.getFunction()+"设置失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if(event.getStatus()==3){
            stopAnim();
            Toast.makeText(context,R.string.toast_setup_success, Toast.LENGTH_SHORT).show();
            backTo();

            //最后再发送一次GETALL获取最新数据
            //得到发送命令的集合
            ArrayList<TagSendCommand> sendCommandList= GetSendCommandList.getGetAllCommandList();
            //设置发送命令额集合
            CommandSendManage.getInstance().setSendCommandList(sendCommandList);
            //开始发送命令
            CommandSendManage.getInstance().startSendCommand();
        }
    }



    @Override
    protected void createPresenter(List<BasePresenter> mPresenters) {

    }

    @Override
    public void onDestroy() {
        if(myHandler!=null){
            myHandler.removeCallbacksAndMessages(null);
            myHandler=null;
        }
        stopAnim();
        super.onDestroy();
    }
}
